require 'csv'

namespace :qcafe do
  desc "Khoi tao khach hang tu 'khach_hang.csv'"
  task :tao_khach_hang => :environment do
    csv_text = File.read('khach_hang.csv')
    csv =  CSV.parse(csv_text, :headers => true)
    csv.each do |row|
      ten_hien_thi = row[0]
      email = row[1]
      so_dien_thoai = Phoner::Phone.parse(row[2])
      ngay_sinh = DateTime.strptime(row[3], "%m/%d/%Y")
      gioi_tinh = rand(2)
      
      nguoi_dung = NguoiDung.find_by_email(email)
      if !nguoi_dung.present?
        NguoiDung.create({
          ten_hien_thi: ten_hien_thi,
          email: email,
          so_dien_thoai: so_dien_thoai.to_s,
          ngay_sinh: ngay_sinh,
          mat_khau: "qcafe123",
          gioi_tinh: gioi_tinh
        })
        else
          nguoi_dung.gioi_tinh = gioi_tinh
          nguoi_dung.save
      end
    end
  end
  
  desc "Khoi tao don hang ngau nhien"
  task :tao_don_hang => :environment do
    so_luong_don_hang = 100
    nguoi_dungs = NguoiDung.where(:is_nhan_vien => false, :is_admin => false, :dang_kich_hoat=> true).all 
    san_phams = SanPham.where(:dang_kich_hoat => true).all
    for i in 1..so_luong_don_hang
      so_luong_sp = 3 + rand(4)
      nguoi_dung = nguoi_dungs[rand(nguoi_dungs.length)]
      puts "Create #{i} for #{nguoi_dung.ten_hien_thi}"
      gio_hang = GioHang.create({
        :nguoi_dung => nguoi_dung
      })
      for j in 1..so_luong_sp
        san_pham = san_phams[rand(san_phams.length)]
        puts " Create #{j} for #{san_pham.slug}"
        sp_mua = SanPhamMua.create({
            :san_pham => san_pham,
            :so_luong => rand(3) + 1,
            :gio_hang => gio_hang,
            :gia_mua => san_pham.co_khuyen_mai(Time.now) ? san_pham.gia_khuyen_mai : san_pham.gia
          })
        gio_hang.san_pham_muas << sp_mua
      end
      gio_hang.da_xac_nhan = true
      gio_hang.thoi_gian_dat_hang = Time.now
      gio_hang.save
      ThongKeGioHang.them_gio_hang(gio_hang)
    end
  end
end